<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="orderVo.userid" clearable class="filter-item" style="width: 160px;" placeholder="请输入用户ID" />
      <el-input v-model="orderVo.id" clearable class="filter-item" style="width: 160px;" placeholder="请输入订单ID" />
      <el-input v-model="orderVo.orderstatus" clearable class="filter-item" style="width: 160px;" placeholder="请输入订单编号" />
      <el-date-picker v-model="orderVo.timeArray" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" class="filter-item"
        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" />
      <el-select v-model="orderVo.orderStatusArray" multiple style="width: 200px" class="filter-item" placeholder="请选择订单状态">
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table :current="subscript" v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit
      highlight-current-row>

      <el-table-column align="center" min-width="100" label="订单编号" prop="ordersn" />

      <el-table-column align="center" label="用户ID" prop="userid" />

      <el-table-column align="center" label="订单状态" prop="orderstatus">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.orderstatus | orderStatusFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="订单金额" prop="goodsprice" />

      <el-table-column align="center" label="支付金额" prop="actualprice" />
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDetail(scope.$index,scope.row)">详情</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="订单详情" width="800">
      <section ref="print">
        <el-form :data="listOnly" label-position="left">
          <el-form-item label="订单编号">
            <span>{{ listOnly.ordersn }}</span>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-tag>{{ listOnly.orderstatus | orderStatusFilter }}</el-tag>
          </el-form-item>
          <el-form-item label="订单用户">
            <span>{{ listOnly.userN }}</span>
          </el-form-item>


          <el-form-item label="用户留言">
            <span>{{ listOnly.message }}</span>
          </el-form-item>
          <el-form-item label="收货信息">
            <span>（收货人）{{ listOnly.userN }}</span>
            <span>（手机号）{{ listOnly.phone }}</span>
            <span>（地址）{{ listOnly.address }}</span>
          </el-form-item>
          <el-form-item label="商品信息">
            <el-table :data="listTable" border fit highlight-current-row>
              <el-table-column align="center" label="商品名称" prop="comTitle" />
              <el-table-column align="center" label="商品编号" prop="ordersn" />
              <el-table-column align="center" label="货品规格" prop="purchsetype" />
              <el-table-column align="center" label="货品价格" prop="goodsprice" />
              <el-table-column align="center" label="货品数量" prop="purchseq" />
              <el-table-column align="center" property="picurl" label="货品图片">
                <template slot-scope="scope">
                  <img :src="scope.row.picurl" width="40">
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="费用信息">
            <span>
              (实际费用){{ listOnly.actualprice }}元 =
              (商品总价){{ listOnly.goodsprice }}元 -
              (优惠减免){{ listOnly.couponprice }}元 -
              (积分减免){{ listOnly.grouponprice }}元
            </span>
          </el-form-item>

        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="printOrder">打 印</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
  import {
    detailOrder,
    listOrder,
    listChannel,
    refundOrder,
    deleteOrder,
    shipOrder
  } from '@/api/order'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import checkPermission from '@/utils/permission' // 权限判断函数

  const statusMap = {
    1: '未付款',
    900: '用户取消',
    103: '系统取消',
    201: '已付款',
    202: '申请退款',
    203: '已退款',
    2: '已发货', //待收货
    4: '用户收货', //售后
    3: '待评价',
    402: '系统收货'
  }

  export default {
    name: 'Order',
    components: {
      Pagination
    },
    filters: {
      orderStatusFilter(status) {
        if (status == -1) {
          status = 900
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        //查询所有数据
        list: [],
        //根据id,或索引查询当前对象返回到详情页面
        listOnly: {},
        listTable: [],
        //传入空值对象实现查询全部
        orderVo: {
          orderstatus: undefined,
          userid: undefined,
          id: undefined,
          timeArray: [],
          orderStatusArray: []
        },
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          id: undefined,
          name: undefined,
          timeArray: [],
          orderStatusArray: [],
          sort: 'add_time',
          order: 'desc',
          orderId: undefined
        },
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        statusMap,
        orderDialogVisible: false,
        orderDetail: {
          order: {},
          user: {},
          orderGoods: []
        },
        shipForm: {
          orderId: undefined,
          shipChannel: undefined,
          shipSn: undefined
        },
        shipDialogVisible: false,
        refundForm: {
          orderId: undefined,
          refundMoney: undefined
        },
        refundDialogVisible: false,
        downloadLoading: false,
        channels: []
      }
    },
    created() {
      this.getList()
      this.getChannel()
    },
    methods: {
      checkPermission,
      getList() {
        this.listLoading = true
        listOrder(this.orderVo).then(response => {
          this.list = response.data.data
          this.list.forEach(item => {
            item.purchsetype = eval(item.purchsetype).toString()
          })
          this.listLoading = false
        }).catch((e) => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      // 查寻详情页面=表格
      getListTable() {
        listOrder(this.orderVo).then(response => {
          this.listTable = response.data.data
          this.listTable.forEach(item => {
            item.purchsetype = eval(item.purchsetype).toString()
          })
          this.listLoading = false
        }).catch((e) => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      getChannel() {
        listChannel().then(response => {
          this.channels = response.data.data
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },


      // 详情页面  --->row(接收当前对象数据)
      handleDetail(input, row) {
        this.listOnly = row
        //添加条件
        this.orderVo.id = row.id
        //调用方法,添加至listTable
        this.getListTable()
        this.orderDialogVisible = true
      },


      handleShip(row) {
        this.shipForm.orderId = row.id
        this.shipForm.shipChannel = row.shipChannel
        this.shipForm.shipSn = row.shipSn

        this.shipDialogVisible = true
        this.$nextTick(() => {
          this.$refs['shipForm'].clearValidate()
        })
      },
      confirmShip() {
        this.$refs['shipForm'].validate((valid) => {
          if (valid) {
            shipOrder(this.shipForm).then(response => {
              this.shipDialogVisible = false
              this.$notify.success({
                title: '成功',
                message: '确认发货成功'
              })
              this.getList()
            }).catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
          }
        })
      },
      handleDelete(row) {
        deleteOrder({
          id: row.id
        }).then(response => {
          this.getList()
          this.$notify.success({
            title: '成功',
            message: '订单删除成功'
          })

        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
      },
      handleRefund(row) {
        this.refundForm.orderId = row.id
        this.refundForm.refundMoney = row.actualPrice

        this.refundDialogVisible = true
        this.$nextTick(() => {
          this.$refs['refundForm'].clearValidate()
        })
      },
      confirmRefund() {
        this.$refs['refundForm'].validate((valid) => {
          if (valid) {
            refundOrder(this.refundForm).then(response => {
              this.refundDialogVisible = false
              this.$notify.success({
                title: '成功',
                message: '确认退款成功'
              })
              this.getList()
            }).catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
          }
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['订单ID', '订单编号', '用户ID', '订单状态', '是否删除', '收货人', '收货联系电话', '收货地址']
          const filterVal = ['id', 'orderSn', 'userId', 'orderStatus', 'isDelete', 'consignee', 'mobile', 'address']
          excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息')
          this.downloadLoading = false
        })
      },
      printOrder() {
        this.$print(this.$refs.print)
        this.orderDialogVisible = false
      }
    }
  }
</script>
